# ~*~ coding: utf-8 ~*~
from flask import current_app
from celery import current_task, shared_task

from apps.extensions import celery
from .celery.decorator import after_app_ready_start, after_app_shutdown_clean, register_as_period_task
from .celery.decorator import get_register_period_tasks
from .celery.utils import create_or_update_celery_periodic_task
from .models import Task


@celery.task
@register_as_period_task(name="task-ops-add-test-6-6", crontab='*/5 * * * *', args=[6, 6])
def add(x, y):
    """ for test
    # Must set this environment, otherwise not no ansible result return
    [root@spider bees]# export PYTHONOPTIMIZE=1
    [root@spider bees]# celery -A apps.ops.celery.app worker --loglevel=debug

    [root@spider bees]# celery -A apps.ops.celery.app beat --loglevel=debug

    [root@spider bees]# python3
    Python 3.6.4 (default, Aug 23 2018, 09:19:44)
    [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from apps.ops.tasks import add
    >>> t=add.delay(2,3)
    >>> t.get()
    5
    >>>
    """
    current_app.logger.debug('current_task-->{}'.format(current_task))
    current_app.logger.debug('current_task.request-->{}'.format(current_task.request))
    current_app.logger.info('Running add method {} + {} = {}'.format(x, y, x+y))
    return x + y


@shared_task
@register_as_period_task(name="task-ops-sub-test-8-6", crontab='*/5 * * * *', args=[8, 6])
def sub(x, y):
    current_app.logger.debug('current_task-->{}'.format(current_task))
    current_app.logger.debug('current_task.request-->{}'.format(current_task.request))
    current_app.logger.info('Running add method {} + {} = {}'.format(x, y, x - y))
    return x - y


@celery.task
@after_app_ready_start
def test_app_start():
    return 'After app ready start Signal TEST'


@celery.task
@after_app_shutdown_clean
def test_app_shutdown():
    return 'After app shutdown clean Signal TEST'


@celery.task
@after_app_ready_start
def create_or_update_registered_periodic_tasks():
    for task in get_register_period_tasks():
        current_app.logger.info('System periodic task: {}'.format(task))
        create_or_update_celery_periodic_task(task)


@celery.task
def run_ansible_task(task_id):
    """
    运行一个Ansible任务
    :param task_id: 任务ID
    :return:
    """
    task = Task.query.get(task_id)
    if task:
        result = task.run()
        return result
    else:
        current_app.logger.error("No task found")
